package com.example.prolyric;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.example.prolyric.database.DatabaseOffice;
import com.example.prolyric.database.LyricDTO;
import com.example.prolyric.songmanager.RateItem;
import com.example.prolyric.songmanager.Song;
import com.example.prolyric.songmanager.SongsManager;

public class ProLyric extends Activity implements View.OnClickListener{
	private ArrayList<Song> listSongs = new ArrayList<Song>();
	private ArrayList<RateItem> listRated  = new ArrayList<RateItem>();
	//private SongManager songManager = new SongManager(this);
	private SongsManager songManager ;
	private int currentSongIndex = 0;
	private ImageButton btnSongList ;
	// Media Player
	private  MediaPlayer mp = new MediaPlayer();
		// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();
	
	//cac thanh phan giao dien
	private ImageButton btnPlay ;
	private ImageButton btnNext, btnPrevious, btnvolume, btnrepeat, btnshuff;
	private ImageButton[] rate = new ImageButton[5];
	private TextView tvSongtitle, tvSongInfo;
	private LoadLyric loadLyric ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pro_lyric);
        songManager = new SongsManager(this);
        listSongs = songManager.getAllSong();
        listRated = songManager.readContentOfRateFile();
        
       // TextView tv_lyric = (TextView) findViewById(R.id.tv_lyric);
        btnPlay = (ImageButton)findViewById(R.id.ibt_play);
        btnNext = (ImageButton)findViewById(R.id.ibt_next);
        btnPrevious = (ImageButton)findViewById(R.id.ibt_previous);
        btnvolume = (ImageButton)findViewById(R.id.btn_volume);
        btnrepeat = (ImageButton)findViewById(R.id.btn_repeat);
        btnshuff = (ImageButton)findViewById(R.id.ibt_shuff);
        rate[0] = (ImageButton)findViewById(R.id.btn_rate1);
        rate[1] = (ImageButton)findViewById(R.id.btn_rate2);
        rate[2] = (ImageButton)findViewById(R.id.btn_rate3);
        rate[3] = (ImageButton)findViewById(R.id.btn_rate4);
        rate[4] = (ImageButton)findViewById(R.id.btn_rate5);
        tvSongtitle = (TextView)findViewById(R.id.tv_songName);
        tvSongInfo = (TextView)findViewById(R.id.tv_songinformation);
        //vo day goi han ra
        loadLyric = (LoadLyric) findViewById(R.id.tv_lyric);
        
        LyricDTO l = new LyricDTO();
        	l.setSongName("Unbreak My Heart");
        	l.setSinger("Toni Braxton");
        	String lyricEn = "Don't leave me in all this pain<br />Don't leave me out in the rain<br />Come back and bring back my smile<br />Come and take the tears away<br />I need your arms to hold me now<br />The nights are so unkind<br />Bring back those nights when I held you beside me<br /><br />[Chorus]<br />Un-break my heart<br />Say you'll love me again<br />Undo this hurt you caused<br />When you walked out the door<br />And walked outta my life<br />Un-cry these tears<br />I cried so many nights<br />Un-break my heart<br />My heart<br /><br />[Verse 2]<br />Take back that sad word good-bye<br />Bring back the joy to my life<br />Don't leave me here with these tears<br />Come and kiss this pain away<br />I can't forget the day you left<br />Time is so unkind<br />And life is so cruel without you here beside me<br /><br />[Chorus]<br /><br />[Bridge]<br />Don't leave me in all this pain<br />Don't leave me out in the rain<br />Bring back the nights when I held you beside me<br /><br />Un-break my heart<br />Say you'll love me again<br />Undo this hurt you caused<br />When you walked out the door<br />And walked outta my life<br />Un-cry these tears<br />I cried so many, many nights<br />Un-break my";
        	
        	Log.d("lyricEn", lyricEn);
			l.setLyricEn(lyricEn);
			l.setLyricVi("Đừng rời em, nỗi đau sau gót<br />Đừng rời em, cơn mưa buồn tênh<br />Về đây anh, nụ cười quay bước<br />Về bên em, giọt lệ còn vương<br />Em cần anh, cái ôm dịu dàng<br />Màn đêm buông cứ sao hững hờ<br />Về với em, nồng ấm có nhau<br /><br />Trái tim ơi xin đừng vỡ tan<br />Nói với em, tiếng yêu nữa thôi<br />Phủ kín nỗi đau qua tháng ngày <br />Tấm cửa vẫn kia ngày anh đi<br />Lạc bước xa khỏi cuộc đời em<br />Giọt lệ ơi xin đ��...");
			l.setLink("http://stream.mp3.zdn.vn/fsfsdfdsfdserwrwq3/f5a4d895fef5881740315a08a60e1bf5/5032fdc5/0/b9/0b961b8095e41189153dbdd44c517d94.mp3");
			l.setCreated(new Date().toString());
			l.getStandarLyric();
		
        DatabaseOffice data = new DatabaseOffice(this);
       // data.insertLyric(l);
       // l = data.getLyricByName("what make you beautiful");
      //  Log.d("test data ", l.getLyricEn());
        
       for(int i = 0 ; i< 5 ; i++) 
       {
    	   rate[i].setOnClickListener(this);
       }
       
       String songUrl = "http://www.loidich.com/ld173-Amazing-Aerosmith.html";
       //cho ni la truyen url  vo, roi han load
     
        
        btnSongList = (ImageButton)findViewById(R.id.ibn_playlist);
        btnSongList.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent i = new Intent(ProLyric.this, ListLibrary.class);
				startActivityForResult(i, 100);
				
			}
		});
        
        btnPlay.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				if(mp.isPlaying())
				{
					mp.pause();
					btnPlay.setImageResource(R.drawable.icon_play);
				}
				else
				{
					mp.start();
					btnPlay.setImageResource(R.drawable.icon_pause);
				}
				
				
			}
		});
        
        btnNext.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(currentSongIndex < (listSongs.size() - 1)){
					playSong(currentSongIndex + 1);
					currentSongIndex = currentSongIndex + 1;
				}else{
					// play first song
					playSong(0);
					currentSongIndex = 0;
				}
				
			}
		});
        
        btnPrevious.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(currentSongIndex > 0){
					playSong(currentSongIndex - 1);
					currentSongIndex = currentSongIndex - 1;
				}else{
					// play last song
					playSong(listSongs.size() - 1);
					currentSongIndex = listSongs.size() - 1;
				}
				
			}
				
			
		});
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_pro_lyric, menu);
        return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(resultCode == RESULT_OK){
    		Bundle bundle = data.getExtras();
    		if(bundle != null)
    		{
    			int type = bundle.getInt("type");
    			String name = bundle.getString("name");
    			int position = bundle.getInt("position");
    			if(type == SongsManager.ALBUMS)
    			{
    				listSongs = songManager.getSongsByAlbum(name);
    			}
    			else if(type == SongsManager.ALL_SONG)
    			{
    				listSongs = songManager.getAllSong();
    			}
    			else if(type == SongsManager.PLAY_LIST)
    			{
    				listSongs = songManager.readContentOfPlaylist(name);
    			}
    			else if(type == SongsManager.TOP_RATE)
    			{
    				listSongs = songManager.getTopRate();
    			}
    				
    			if(listSongs == null)
    				Log.d("trang thai play lis", "rong");
    			else 
    				Log.d("path mp3", listSongs.get(0).getAudioFilePath());
    			MediaPlayer mp = new MediaPlayer();
    			try {
    				mp.setDataSource(listSongs.get(0).getAudioFilePath());
    				//mp.prepare();
    				//mp.start();
				} catch (Exception e) {
					// TODO: handle exception
				}
    			currentSongIndex = position;
    			playSong(currentSongIndex);
    			Log.d("du lieu tra ve ", type + "  " + name + "  " + position);
    		}
    		
    		else 
    			Log.d("trang thai bundle","bundle rong me no roi");
    		//Log.v("du lieu tra ve", "type: "+);
    	}
    }
    
    
    public void  playSong(int songIndex){
		// Play song
		try {
        	mp.reset();
			mp.setDataSource(listSongs.get(songIndex).getAudioFilePath());
			mp.prepare();
			mp.start();
			// Displaying Song title
			String songTitle = listSongs.get(songIndex).getSong_display_name();
			songTitle =songTitle.substring(0, songTitle.length()-4);
        	tvSongtitle.setText(songTitle);
        	tvSongInfo.setText(songTitle);
			
        	// Changing Button Image to pause image
			btnPlay.setImageResource(R.drawable.icon_pause);
			
			// set Progress bar values
			//songProgressBar.setProgress(0);
			//songProgressBar.setMax(100);
			
			// Updating progress bar
			//updateProgressBar();		
			
			//getRating of current song
			String songname = listSongs.get(songIndex).getSong_display_name();
			songname = songname.substring(0,songname.lastIndexOf(" - "));
			Log.d("songname to search", songname);
			  loadLyric.getLyricBySongname(this,songname);
			setRateforUI(getRateOfCurrentSong());
			
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

    
    //
	public void onClick(View v) {
		int rateValue = 0;
		for(int i = 0 ;i<this.rate.length ; i++)
		{
			if(this.rate[i] == v)
			{
				rateValue = i;
				for(int j= 0 ; j<=i; j++)
					rate[j].setImageResource(R.drawable.icon_rating_importan);
				for(int j = i+1 ; j<rate.length; j++)
					rate[j].setImageResource(R.drawable.icon_rating_not_importan);
			} 
			
			
		}
		
		songManager.modifileRate(listSongs.get(currentSongIndex), rateValue);
		//songManager.deleteRateFile();
		
	} 
	
	
	/*
	 * set rate for a song
	 * get rate of a song then set for rates of UI
	 * */
	
	public void setRateforUI(int ratevalue)
	{
		if(ratevalue>=0)
		{
			for(int i = 0 ; i<= ratevalue ; i++)
			{
				rate[i].setImageResource(R.drawable.icon_rating_importan);
				
			}
			for(int i = ratevalue+1 ; i<5; i++)
			{
				rate[i].setImageResource(R.drawable.icon_rating_not_importan);
			}
		}
	}
	
	public int getRateOfCurrentSong()
	{
		int rate = -1;
		Song s= listSongs.get(currentSongIndex);
		int i = 0 ;
		
		while(i<listRated.size())
		{
			if(s.getAudioFilePath().equals(listRated.get(i).getAudioFilePath()))
			{
				rate = listRated.get(i).getRate();
				break;
			}
			i++;
		}
		return rate;
		
	} 
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mp.release();
	}
	
}


